<?php
namespace Operator\Controller;
/**
 * 后台线路管理
 */
class LineController extends BaseController{

//*****************************************

        /**
     * 线路添加
     */
    public function add(){
        //第一步加载页面和数据
        $Mcitys = M('Areas');
        $areas = $Mcitys->where('areaType=1')->select();
        $Mtheme = M('Line_theme');
        $themes = $Mtheme->select();
        $Mtraffic = M('Public_single_traffic');
        $traffics = $Mtraffic->select();
        $Msupplier = M('Public_single_supplier');
        $hotels = $Msupplier->where("type=2")->select();
        $scenics = $Msupplier->where("type=4")->select();
        $countrys = $Mcitys->where('areaType=4')->select(); 
        $this->assign("countrys",$countrys);
        $this->assign('step','1');
        $this->assign('hotel',$hotels);
        $this->assign('scenic',$scenics);
        $this->assign('traffics',$traffics);
        $this->assign('themes',$themes);
        $this->assign("areas",$areas);
        $this->display('form_step1');
    }

    // 第一步入库
    public function step1_action(){
        //线路名称
        $data['line_name'] = I('line_name');
        //团号
        $data['group_num'] = I('group_num');
        //行程天数
        $data['travel_days'] = I('travel_days');
        //出发城市
        $data['origin_id'] = I('cityId');
        //目的城市
        $data['destination_id'] = I('cityId_dist');
        //线路主题
        $arr = I('theme');
        $tid = '';
        $tname = '';
        $Mtheme = M('Line_theme');
        //线路类型  
        $data['line_type'] =  I("line_type")?I("line_type"):0;

        if(count($arr) > 0){

            foreach ($arr as $key => $val) {
               $name = $Mtheme->where('theme_id='.$val)->getField('theme_name');
               $tid .= $val.",";     
               $tname .= $name.",";
            }

            $tid   = rtrim($tid, ',');
            $tname = rtrim($tname, ',');
        }else{

            $tid = $arr;
            $tname = $Mtheme->where('theme_id='.$tid)->getField('theme_name');

        }

        $data['theme_id'] = $tid;
        $data['theme_name'] = $tname;

        //预收客人
        $data['guests_num'] = I('guests_num');
        //截止收团日期
        $data['till_day'] = I('till_day');
        //出团前多少天开始预订
        $data['book_day'] = I('book_day');
        //出团时间
        $data['start_time'] = strtotime(I('start_time'));
        //结束时间
        $data['end_time']   = strtotime(I('end_time'));
        //默认是否天天出团
        $data['is_everyday'] = I('is_everyday');
        //去交通方式-供应商-座位
        //回交通方式-供应商-座位
        //酒店类型-座位
        //景区类型-座位
        
        $Mline = M('Public_line');
        $act = I('step')+1;
        $insert_id = $Mline->add($data);
        if ($insert_id) {
            $_SESSION['line_id'] = $insert_id;
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    } 
    //第二步加载页面
    public function form_step2(){ 
    
        $this->assign('step','2');
        $this->display('form_step2');
    } 

    //第二步入库
    public function step2_action(){

        $act = $_POST['step']+1;
        if (1==1) {
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    }

    //第三步加载页面
    public function form_step3(){
        $Mline = M('Public_line');
        $days = $Mline->where('line_id='.$_SESSION['line_id'])->getField('travel_days');
        $this->assign("travel_days",$days);
        $this->assign('step','3');
        $this->display('form_step3');
    } 
    //第三步入库
    public function step3_action(){

        $act = $_POST['step']+1;  
        //入库处理
        $names = I();
        //总共days天行程
        $days = $names['travel_days'];
        //$arr接收传递过来的行程数据下标对应第几天行程
        $arr = $names['arr'];
        //线路id
        $line_id  = intval($_SESSION['line_id']);
        //声明数组
        $trip_ids = array();

        //游玩项目数据
        //购物项目数据
        foreach ($names['arr'] as $k => $v) {

            $plays = '';
            $shoppings = '';  
            foreach ($v as $key => $val) {

                //判断如果$val是数组就是游戏项目或者购物项目
                if( $key == 'play' || $key == 'shopping'){
                        //   echo '<pre>';
                        // var_dump($key);
                        // echo '<hr/>';
                   if($key == 'play'){
                        //游玩项目入库
                        //判断有几个项目
                        $len = count($val['name']);
                        //用数组记录下入表的play_id
                        $play_ids = array();
                         //用数组记录下入表的play_id
                        $shopping_ids = array();
    
                        $Mplay = M('Public_play');
                        for ($i=0; $i < $len ; $i++) { 
                            # code...
                            $da['name'] = $val['name'][$i];
                            $da['price'] = floatval($val['price'][$i]);
                            $da['note'] = $val['note'][$i];
                            $da['line_id'] = intval($line_id);
                            $da['create_time'] = time();
                            $da['operator_id'] = intval($_SESSION['oto_mall']['operator_user']['operator_id']);

                            $insert_id = $Mplay->add($da);
                            if($insert_id){
                                array_push($play_ids, $insert_id);
                            }
                        }

                   }else{
                    //购物项目入库
                    //判断有几个项目
                        $len = count($val['shopping_name']);
                       
                        $Mshopping = M('Public_shopping');
                        for ($i=0; $i < $len ; $i++) { 
                            # code...
                            $dat['shopping_name'] = $val['shopping_name'][$i];
                            $dat['product'] = $val['product'][$i];
                            $dat['stay_time'] = $val['stay_time'][$i];
                            $dat['instructions'] = $val['instructions'][$i];
                            $dat['line_id'] = intval($line_id);
                            $dat['create_time'] = time();
                            $dat['operator_id'] = intval($_SESSION['oto_mall']['operator_user']['operator_id']);
                            $insert_id = $Mshopping->add($dat);
                            if($insert_id){
                                array_push($shopping_ids, $insert_id);
                            }
                        }
                   }
                }

                
  
            }

            //入库行程表 组装游玩项目id逗号隔开的字符串，组装购物项目id逗号形式存储  
                foreach ($play_ids as $k => $a) {
                    $plays .= $a.",";
                }
                foreach ($shopping_ids as $k => $b) {
                    $shoppings .= $b.",";
                }


                // echo '<hr/>';
                // var_dump($plays,$shoppings);
               $plays = rtrim($plays,',');
               $shoppings = rtrim($shoppings,",");

             //$k等于多少就是第几天行程
                $data['line_id'] = intval($line_id);
                $data['current_day'] = $k;
                $data['trip_title']  = $v['trip_title'];
                $data['features'] = $v['features'];
                $data['lodging']  = $v['lodging'];
                $data['scenic_spot'] = $v['scenic_spot'];
                $data['trip_details'] = $v['trip_details'];
                $data['operator_id'] = intval($_SESSION['oto_mall']['operator_user']['operator_id']);
                $data['play_id']     = $plays;
                $data['shopping_id'] = $shoppings;
                $Mtrip = M('Public_trip');
                $trip_id = $Mtrip->add($data);
               
                if($trip_id){
                    array_push($trip_ids,$trip_id);
                }
        }
 
        foreach ($trip_ids as $kk => $c) {
           $trips .= $c.",";
        }
        $trips = rtrim($trips,',');
        //吧行程id存入线路表$line_id
        $Mline = M('Public_line');
        $res['trip_id'] = $trips;


        if ($Mline->where('line_id='.$line_id)->save($res)) {
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    }
    //第四步加载页面
    public function form_step4(){
        //读取签证内容遍历
        $Mvisa = M('Public_visa');
        $visa = $Mvisa->select();
        $this->assign("visa",$visa);
        $this->assign('step','4');
        $this->display('form_step4');
    } 
    //选中签证ajax返回相关数据
    public function visa_ajax(){
        $id = I('visa_id');
        $Mvisa = M('Public_visa');
        $data  = $Mvisa->where("visa_id=".$id)->select();
        $this->ajaxReturn($data); 
    }

    //第四步入库
    public function step4_action(){

        $act = $_POST['step']+1;
        //线路id
        $line_id  = intval($_SESSION['line_id']);

        $data['visa_id'] = intval(I('visa_id'));
        $Mline = M('Public_line'); 
        if ($Mline->where('line_id='.$line_id)->save($data)) {
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    }
    //第五步加载页面
    public function form_step5(){

        $this->assign('step','5');
        $this->display('form_step5');
    } 
    //第五步入库
    public function step5_action(){

        $act = I('step')+1;
        //入库oto_public_additional_product表
        $line_id = intval($_SESSION['line_id']);
        $post = I();
        //统计有多少条产品
        $num = count($post['product_name']);
        //存入附属产品表oto_public_additional_product
        $Madditional_product = M('line_additional_product');
        //新建一个数组存放插入成功的id，给后面存入线路表用
        $ids = array();
        $str = '';

        //更新新的附属产品入库成功，根据line_id删除相应的产品
        $Madditional_product->where('line_id='.$line_id)->delete();

        for($i=0;$i<$num;$i++){
            $data = array();
            $data['line_id'] = $line_id;
            $data['product_name'] = $post['product_name'][$i];
            $data['product_price']= intval($post['product_price'][$i]);
            $data['product_sort'] = intval($post['product_post'][$i]);
            $data['is_show']      = $post['is_show'][$i]?$post['is_show'][$i]:1;
            $data['operator_id']  = intval($_SESSION['oto_mall']['operator_user']['operator_id']);
            $insert_id = $Madditional_product->add($data);
            
            if($insert_id){
                array_push($ids,$insert_id);
            }
        }

        // var_dump($ids);
        //组装逗号隔开的id集合
        foreach ($ids as $ke => $va) {
            # code...
            $str .= $va.",";
        }

        $str = rtrim($str,',');

        $Mline = M('Public_line');
        
        $res['product_id'] = $str;
        $last = $Mline->where('line_id='.$line_id)->save($res);
     
        if($last != false) {
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    }
    //第六步加载页面
    public function form_step6(){
        //销售方式
        $Mchannel = M('Sales_channel_type');
        $sales_channel = $Mchannel->select();
        //运营商列表
        $Moperator = M('Operator');
        $users = $Moperator->where('pid=0')->select();
        //门店列表
        $stores = $Moperator->where('is_store=1')->select();

        $this->assign('stores',$stores);
        $this->assign('users',$users);
        $this->assign('channels',$sales_channel);
        $this->assign('step','6');
        $this->display('form_step6');
    } 
    //第六步入库
    public function step6_action(){
        var_dump('保存成！显示列表！');exit;
        $act = $_POST['step']+1;
        if (1==1) {
            $this->success('保存成功',U('line/form_step'.$act));
        }else{
            $this->error('保存失败');
        }
    }





     /**
    *   ajax查询酒店对应的房间
    */ 

    public function hotel2room(){
        $supplier_id = I('supplier_id');
        //查询他的上级
        $Mroom_price = M('Public_single_room_price');
        $room_ids = $Mroom_price->where('supplier_id='.$supplier_id)->select();
        $Mroom = M('Public_single_room');
        $res = array();
        foreach ($room_ids as $key => $val) {
            # code...
            $res[] = $Mroom->where('room_id='.$val['room_id'])->select(); 
         } 

        if($res){
            $data['status'] = 1;
            $data['rooms'] = $res;
        }else{
            $data['status'] = 0;
        }

        $this->ajaxReturn($data);
        

    }


    /**
    *   ajax查询交通方式
    */ 

    public function find_traffic(){
        $cityId = I('cityId');
        //查询他的上级
        $Mtraffic = M('Public_single_traffic');
        $res = $Mtraffic->select();
        if($res){
            $data['status'] = 1;
            $data['traffics'] = $res;
        }else{
            $data['status'] = 0;
        }

        $this->ajaxReturn($data);
        

    }

    /**
    *   ajax增加酒店
    */ 

    public function add_hotel(){
        //查询他的上级
        $Mhotel = M('Public_single_supplier');
        $res = $Mhotel->where('type=2')->select();
        if($res){
            $data['status'] = 1;
            $data['hotels'] = $res;
        }else{
            $data['status'] = 0;
        }

        $this->ajaxReturn($data);
        

    }

     /**
    *   ajax增加景区
    */ 

    public function add_scenic(){
        //查询他的上级
        $Mscenic = M('Public_single_supplier');
        $res = $Mscenic->where('type=4')->select();
        if($res){
            $data['status'] = 1;
            $data['scenic'] = $res;
        }else{
            $data['status'] = 0;
        }

        $this->ajaxReturn($data);
        

    }




    /**
    *   根据当前传递参数筛选下级的要展示的地区
    */ 

    public function show_areas(){
        $cityId = I('cityId')?I('cityId'):0;
        $kind = I('kind');
        //查询他的上级
        $Marea = M('Areas');

        //封装传递给js的数组
        $rs = array();

        $condition = " and isShow=1 and areaFlag=1";

        switch ($kind) {
            case 'province':
                # 省内
            $parentId = $Marea->where("areaId=".$cityId.$condition)->getField("parentId");
            $parent = $Marea->where("parentId=".$parentId)->select();

            $arr  = array();
            $arr  = $parent;
            //设置一个数组专门存父级id集合
            $ids = array();
            foreach ($arr as $k => $v) {
                # code...查询对应的下级，健（父）值对（儿）形式
                $son = $Marea->where("parentId=".$v['areaId'].$condition)->select();   
                $arr[$k]['ids'] = $son; 
            }

            // $data['status'] = 1;
            // $data['citys'] = $parentId;
            // $this->ajaxReturn($data);
            
                break;
            case 'inbound':
                # 国内
            $parentId = $Marea->where("areaId=".$cityId.$condition)->getField("parentId");
            if($parentId != 0){
                $parentId = $Marea->where("areaId=".$parentId.$condition)->getField("parentId");   
            }
            $parent = $Marea->where("parentId=".$parentId.$condition)->select();

            $arr  = array();
            $arr  = $parent;
            //设置一个数组专门存父级id集合
            $ids = array();
            foreach ($arr as $k => $v) {
                # code...查询对应的下级，健（父）值对（儿）形式
                $son = $Marea->where("parentId=".$v['areaId'].$condition)->select();   
                $arr[$k]['ids'] = $son; 
            }

                break;
            case 'outbound':
                # 出境
            $parent = $Marea->where("areaType=4".$condition)->select();

            $arr  = array();
            $arr  = $parent;
            //设置一个数组专门存父级id集合
            $ids = array();
            foreach ($arr as $k => $v) {
                # code...查询对应的下级，健（父）值对（儿）形式
                $son = $Marea->where("parentId=".$v['areaId'].$condition)->select();   
                $arr[$k]['ids'] = $son; 
            }
                break;
            
            default:
                # code...
                break;
        }

        $data['status'] = 1;
        $data['citys'] = $arr;
        $this->ajaxReturn($data);
        

    }


    /**
    *   根据交通方式id查询对应的供应商
    */ 

    public function traffic2msg(){

        $id = I('id');
        $Msupplier = M('Public_single_supplier');
        $Mseat     = M('Public_single_traffic_seat');
        $where     = array('traffic_id'=>$id);

        $suppliers = $Msupplier->where("find_in_set(".$id.",traffic_ids)")->select();

        $seats     = $Mseat->where($where)->select();

        if(empty($suppliers) && empty($seats)){

             $rt['status'] = 0;
             
        }else{
            

            if($suppliers && $seats){
                $rt['status'] = 1;       
                $rt['suppliers']    = $suppliers;
                $rt['seats']        = $seats;  
    
            }else{

                 if($suppliers){
                    $rt['status'] = 2;         
                    $rt['suppliers']    = $suppliers;
                    
                }

                if($seats){
                    $rt['status'] = 3;
                    $rt['seats']        = $seats;  
                }

            }

           


        }

        $this->ajaxReturn($rt);

    }
    




    /**
     * 修改权限
     */
    public function edit(){
        $data=I('post.');
        $map=array(
            'id'=>$data['id']
            );
        $result=D('AuthRule')->editData($map,$data);
        if ($result) {
            $this->success('修改成功',U('Rule/index'));
        }else{
            $this->error('修改失败');
        }
    }

    /**
     * 删除权限
     */
    public function delete(){
        $id=I('get.id');
        $map=array(
            'id'=>$id
            );
        $result=D('AuthRule')->deleteData($map);
        if($result){
            $this->success('删除成功',U('Rule/index'));
        }else{
            $this->error('请先删除子权限');
        }

    }
//*******************用户组**********************
    /**
     * 用户组列表
     */
    public function group(){
        $data=D('AuthGroup')->where(array('admin_id'=>$this->admin_id))->select();
        $assign=array(
            'data'=>$data
            );
        $this->assign($assign);
        $this->display();
    }

    /**
     * 添加用户组
     */
    public function add_group(){
        $data=I('post.');
        unset($data['id']);
        $data['admin_id']=$this->admin_id;
        $result=D('AuthGroup')->addData($data);
        if ($result) {
            $this->success('添加成功',U('Rule/group'));
        }else{
            $this->error('添加失败');
        }
    }

    /**
     * 修改用户组
     */
    public function edit_group(){
        $data=I('post.');
        $map=array(
            'id'=>$data['id']
            );
        $result=D('AuthGroup')->editData($map,$data);
        if ($result) {
            $this->success('修改成功',U('Rule/group'));
        }else{
            $this->error('修改失败');
        }
    }

    /**
     * 删除用户组
     */
    public function delete_group(){
        $id=I('get.id');
        $map=array(
            'id'=>$id
            );
        $result=D('AuthGroup')->deleteData($map);
        if ($result!==false) {
            $this->success('删除成功',U('Rule/group'));
        }else{
            $this->error('删除失败');
        }
    }

//*****************权限-用户组*****************
    /**
     * 分配权限
     */
    public function rule_group(){



        if(IS_POST){
            $data=I('post.');
            $map=array(
                'id'=>$data['id']
                );
            $data['rules']=implode(',', $data['rule_ids']);
            unset($data['rule_ids']);
            $data['admin_id']=$this->admin_id;
            $result=D('AuthGroup')->editData($map,$data);
            if ($result) {
                $this->success('操作成功',U('Rule/group'));
            }else{
                $this->error('操作失败');
            }
        }else{
            $id=I('get.id');
            // 获取用户组数据
            $group_data=M('dealer_auth_group')->where(array('id'=>$id))->find();
            $group_data['rules']=explode(',', $group_data['rules']);
            // 获取规则数据
            $rule_data=D('AuthRule')->getTreeData('level','id','title');
            $assign=array(
                'group_data'=>$group_data,
                'rule_data'=>$rule_data
                );
            $this->assign($assign);
            $this->display();
        }

    }
//******************用户-用户组*******************
    /**
     * 添加成员
     */
    public function check_user(){
        $username=I('username','');
        $group_id=I('group_id');

        $group_name=M('dealer_auth_group')->where(array('admin_id'=>$this->admin_id))->getFieldById($group_id,'title');

        $uids=D('AuthGroupAccess')->getUidsByGroupId($group_id);
        // 判断用户名是否为空
        if(empty($username)){
            $user_data='';
        }else{
            //区分哪一个平台的会员
            $userInfo=session('dealer_user');
            $where="operator_name like '%{$username}%'";
            if($userInfo['pid']==0){
                $where.=" and (operator_id={$userInfo['operator_id']} or pid={$userInfo['operator_id']})";
            }else{
                $where.=" and (operator_id={$userInfo['pid']} or pid={$userInfo['pid']})";
            }
            $user_data=M('operator')->where($where)->select();
        }
        $assign=array(
            'group_name'=>$group_name,
            'uids'=>$uids,
            'user_data'=>$user_data,
            'username'=>$username,
            'group_id'=>$group_id,
            );
        $this->assign($assign);
        $this->display();
    }

    /**
     * 添加用户到用户组
     */
    public function add_user_to_group(){
        $data=I('get.');
        $map=array(
            'uid'=>$data['uid'],
            'group_id'=>$data['group_id']
            );
        $count=M('dealer_auth_group_access')->where($map)->count();
        if($count==0){
            unset($data['username']);
            D('AuthGroupAccess')->addData($data);
        }
        $this->success('操作成功',U('Rule/check_user',array('group_id'=>$data['group_id'],'username'=>$data['username'])));
    }

    /**
     * 将用户移除用户组
     */
    public function delete_user_from_group(){
        $map=I('get.');
        $result=D('AuthGroupAccess')->deleteData($map);
        if ($result) {
            $this->success('操作成功',U('Rule/admin_user_list'));
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 管理员列表
     */
    public function admin_user_list(){
        $data=D('AuthGroupAccess')->getAllData();
        $assign=array(
            'data'=>$data
            );
        $this->assign($assign);
        $this->display();
    }

    /**
     * 添加管理员
     */
    public function add_admin(){
        if(IS_POST){
            $data=I('post.');
            $result=D('Users')->addData($data);
            if($result){
                if (!empty($data['group_ids'])) {
                    foreach ($data['group_ids'] as $k => $v) {
                        $group=array(
                            'uid'=>$result,
                            'group_id'=>$v
                            );
                        D('AuthGroupAccess')->addData($group);
                    }                   
                }
                // 操作成功
                $this->success('添加成功',U('Rule/admin_user_list'));
            }else{
                $error_word=D('Users')->getError();
                // 操作失败
                $this->error($error_word);
            }
        }else{
            $data=D('AuthGroup')->where(array('admin_id'=>$this->admin_id))->select();
            $assign=array(
                'data'=>$data
                );
            $this->assign($assign);
            $this->display();
        }
    }

    /**
     * 修改管理员
     */
    public function edit_admin(){
        if(IS_POST){
            $data=I('post.');
            // 组合where数组条件
            $uid=$data['id'];
            $map=array( 'operator_id'=>$uid);
            // 修改权限
            D('AuthGroupAccess')->deleteData(array('uid'=>$uid));
            foreach ($data['group_ids'] as $k => $v) {
                $group=array(
                    'uid'=>$uid,
                    'group_id'=>$v
                    );
                D('AuthGroupAccess')->addData($group);
            }
            $data=array_filter($data);
            // 如果修改密码则md5
            if (!empty($data['password'])) {
                $data['password']=md5($data['password']);
            }
            $result=D('Users')->editData($map,$data);
            if($result){
                // 操作成功
                $this->success('编辑成功',U('Rule/edit_admin',array('id'=>$uid)));
            }else{
                $error_word=D('Users')->getError();
                if (empty($error_word)) {
                    $this->success('编辑成功',U('Rule/edit_admin',array('id'=>$uid)));
                }else{
                    // 操作失败
                    $this->error($error_word);                  
                }

            }
        }else{
            $id=I('get.id',0,'intval');
            // 获取用户数据
            $user_data=M('operator')->find($id);
            // 获取已加入用户组
            $group_data=M('AuthGroupAccess')
                ->where(array('uid'=>$id))
                ->getField('group_id',true);
            // 全部用户组
            $data=D('AuthGroup')->where(array('admin_id'=>$this->admin_id))->select();
            $assign=array(
                'data'=>$data,
                'user_data'=>$user_data,
                'group_data'=>$group_data
                );
            $this->assign($assign);
            $this->display();
        }
    }
}
